<?php
session_start();
require('config.ini.php');
if (!isset($_POST['action'])) {
	header("Location: index.php");
} else {
	if(isset($_POST['action'])){
            $action = $_POST['action'];
        } else {
            $action = $_GET['action'];
    }
}
function insgenfood(){
	$a = "asdf";
	return $a;
}
switch ($action) {
    case "login":
        $loginusername = $_POST['username'];
        $loginpassword = $_POST['userpassword'];
        $ipaddress = $_SERVER['REMOTE_ADDR'];
        $sql="SELECT userid,usertype FROM userdata WHERE userid = '$loginusername' AND password = PASSWORD('$loginpassword') AND usertype='1' AND userstatus = '1'";
        $result = mysql_query($sql);
        $row = mysql_fetch_array($result);
        $numrow = mysql_num_rows($result);
        if($numrow == 1) {
            session_register("userid");
            session_register("usertype");
            $_SESSION['userid'] = $row['0'];
            $_SESSION['usertype'] = $row['1'];
            $sql="INSERT INTO userlog (userid,logdatetime,ipaddress) VALUES ('$loginusername',NOW(),'$ipaddress')";
            mysql_query($sql);
                if($row['1']==0) { //admin
                    header("Location: admin.php");
                } else { //user
                    header("Location: index.php");
                }
            mysql_free_result($result);
            mysql_close($link);
        } else {
            header("Location: index.php");
        }
    break;
	
	case "regis":
	$fuserid=$_POST['userid'];
	$password=$_POST['password'];
	$username=$_POST['username'];
	$usersname=$_POST['usersname'];
	$address=$_POST['address'];
	$province=$_POST['province'];
	$zipcode=$_POST['zipcode'];
	$email=$_POST['email'];
	$tel=$_POST['tel'];
	$mobile=$_POST['mobile'];
	$brithday = $_POST['brithday'];
	$sex=$_POST['sex'];
	$userhigh=$_POST['userhigh'];
	$userweight=$_POST['userweight'];
	if(isset($_POST['sms'])) {
		$sms = 1;
	} else {
		$sms = 0;
	}
	$isEnglish = ereg("^[a-zA-Z0-9' ']+$", $fuserid);
	if($isEnglish==false){
		 echo "<script> history.back(); </script>";
	} else {
	$sql="INSERT INTO userdata(userid,password,username,usersname,address,province,zipcode,email,tel,mobile,brithday,sex,userhigh,userweight,usertype,sms)VALUES('$fuserid', PASSWORD('$password') ,'$username','$usersname','$address','$province','$zipcode','$email','$tel','$mobile',STR_TO_DATE('$brithday','%d-%m-%Y'),'$sex','$userhigh','$userweight','1','$sms')";
	mysql_query($sql);
	$sql="SELECT max(diseaseid) AS numdisease FROM disease";
	$result=mysql_query($sql);
	$row=mysql_fetch_object($result);
	$loopcheckbox=$row->numdisease;
	$sql="";
		for ($i=1;$i<=$loopcheckbox;$i++) {
		$str = "disease";
		$str .= "$i";
		$diseaseid = $_POST[$str];
		if ($diseaseid != ""){ 
			$sql = "INSERT INTO userdisease(userid,diseaseid) VALUES('$fuserid','$diseaseid')"; 
			mysql_query($sql);
			}
		}
	session_register("userid");
	session_register("usertype");
	$_SESSION['userid'] = $fuserid;
	$_SESSION['usertype'] = 1;
	mysql_free_result($result);
	mysql_close($link);
	header("Location: index.php");
	}
	break;
	
	case "edituser":
	$userid=$_SESSION['userid'];
	$password=$_POST['password'];
	$username=$_POST['username'];
	$usersname=$_POST['usersname'];
	$address=$_POST['address'];
	$province=$_POST['province'];
	$zipcode=$_POST['zipcode'];
	$tel=$_POST['tel'];
	$mobile=$_POST['mobile'];
	$userhigh=$_POST['userhigh'];
	$userweight=$_POST['userweight'];
	$email=$_POST['email'];
	if(isset($_POST['sms'])) {
		$sms=1;
	} else { 
		$sms=0;
	}
	if(isset($_POST['ckchange'])) {
		$sql="UPDATE userdata SET password=PASSWORD('$password'),username='$username',usersname='$usersname',address='$address',province='$province',zipcode = '$zipcode',tel='$tel',mobile='$mobile',userhigh='$userhigh',userweight='$userweight',sms='$sms' WHERE userid='$userid'";
	} else {
		$sql="UPDATE userdata SET username='$username',usersname='$usersname',address='$address',province='$province',zipcode = '$zipcode',tel='$tel',mobile='$mobile',userhigh='$userhigh',userweight='$userweight',sms='$sms' WHERE userid='$userid'";
	}
	mysql_query($sql);
	$sql="DELETE FROM userdisease WHERE userid='$userid'";
	mysql_query($sql);
	$sql="SELECT max(diseaseid) AS numdisease FROM disease";
	$result=mysql_query($sql);
	$row=mysql_fetch_object($result);
	$loopcheckbox=$row->numdisease;
	$sql="";
	for ($i=1;$i<=$loopcheckbox;$i++) {
		$str = "disease";
		$str .= "$i";
		$diseaseid = $_POST[$str];
		if ($diseaseid != ""){ 
			$sql = "INSERT INTO userdisease(userid,diseaseid) VALUES('$userid','$diseaseid')"; 
			mysql_query($sql);
		}
	}
	header('location: profile.php');
	break;
	
	case "reportmeal":
	$userid = $_SESSION['userid'];
	$menudate = $_POST['mealdate'];
	$menumeal = $_POST['menumeal'];
	$foodid = $_POST['foodid'];
	$foodcc = $_POST['foodcc'];
    $sql="INSERT INTO usermenudiet (userid,menudate,menumeal,foodid,foodcc) VALUES ('$userid',STR_TO_DATE('$menudate','%d-%m-%Y'),'$menumeal','$foodid','$foodcc')";
	mysql_query($sql);
	if(mysql_affected_rows() == "-1"){
		$sql = "UPDATE usermenudiet SET foodcc=foodcc+$foodcc WHERE userid='$userid' AND menudate=STR_TO_DATE('$menudate','%d-%m-%Y') AND menumeal='$menumeal' AND foodid='$foodid'";
		mysql_query($sql);
	}
	mysql_close($link);
	header("Location: reportfood.php?reportday=$menudate");
	break;
	
	case "genfood":
	$userid = $_SESSION['userid'];
	$updown = $_POST['course'];
    $kg = $_POST['kg'];
    $weight = $_POST['weight'];
	$resultperday = $weight*25;
	if ($updown ==1 ) {
		$resultcc = $resultperday+500;
	} else {
		$resultcc = $resultperday-500;
	}
	$week = round($kg/0.5);
	$resultpermeal = round($resultcc/3);
	$setpermeal = $resultpermeal;
	$day = $week;
	$strmenuid = "''";
	$sql = "SELECT userdisease.diseaseid FROM userdisease WHERE userdisease.userid = '$userid'";
	$result = mysql_query($sql);
	while ($row=mysql_fetch_array($result)) {
		$strmenuid .= ",'$row[0]'";
	}
	$setstrmenuid = $strmenuid;
	
	for ($w=0;$w<=$day;$w++) {
		$menudate = date("Y-m-d",strtotime("now + $w day"));
		if($updown == 2){
			$lm = 2;
			$sqlinsert = "INSERT INTO menudietexample (menudate,menumeal,foodid,foodcc,userid) VALUES ('$menudate','3','0','0','$userid')";
			mysql_query($sqlinsert);
		} else {
			$lm = 3;
		}
			for ($m=1;$m<=$lm;$m++) {
				$menu = array();
				$menuid = array();
				$totalcc = 0;
				$sql = "select foodid from food";
				$result = mysql_query($sql);
				$numfood = mysql_num_rows($result);
					for ($i=1;$i<=$numfood;$i++) {
						if ($totalcc <= $resultpermeal) {
							//echo $sql = "SELECT food.foodid, food.foodname, food.totalcallory FROM food WHERE food.foodid NOT IN (SELECT userdisease.diseaseid FROM userdisease WHERE userdisease.userid = '$userid' ) and food.totalcallory <= $resultpermeal AND food.foodid NOT IN ($strmenuid) order by rand()";
							$sql = "SELECT food.foodid, food.foodname, food.totalcallory FROM food WHERE food.status = '1' AND food.totalcallory <= $resultpermeal AND food.foodid NOT IN ($strmenuid) order by rand()";
							
							$result = mysql_query($sql);
							$row = mysql_fetch_array($result);
							$menu[] = $row;
							$totalcc = $totalcc+$row[2];
							$resultpermeal = $resultpermeal - $totalcc;
							$menuid[] = $row['0'];
							$strmenuid .= ",'$row[0]'";
							//print_r($row);
								if ($row[0]!=="") {
									$sqlinsert = "INSERT INTO menudietexample (menudate,menumeal,foodid,foodcc,userid) VALUES ('$menudate','$m','$row[0]','$row[2]','$userid')";
									mysql_query($sqlinsert);
							}
						} else {
						//echo $i;
							$strmenuid = $setstrmenuid;
							$totalcc = 0;
							$resultpermeal = $setpermeal;
							break;
						}
					}
			}
		}
		
		mysql_free_result($result);
		mysql_close($link);
		$menudate = date("d-m-Y");
		header("location: reportfood.php?reportday=$menudate");
	break;
	
	case "delnewgenfood":
	$userid = $_SESSION['userid'];
	$updown = $_POST['course'];
	$sql = "DELETE FROM menudietexample WHERE userid = '$userid'";
	mysql_query($sql);
	$kg = $_POST['kg'];
    $weight = $_POST['weight'];
	$resultperday = $weight*25;
	if ($updown ==1 ) {
		$resultcc = $resultperday+500;
	} else {
		$resultcc = $resultperday-500;
	}
	$week = round($kg/0.5);
	$resultpermeal = round($resultcc/3);
	$setpermeal = $resultpermeal;
	$day = $week;
	$strmenuid = "''";
	$sql = "SELECT userdisease.diseaseid FROM userdisease WHERE userdisease.userid = '$userid'";
	$result = mysql_query($sql);
	while ($row=mysql_fetch_array($result)) {
		$strmenuid .= ",'$row[0]'";
	}
	$setstrmenuid = $strmenuid;
	
	for ($w=0;$w<=$day;$w++) {
		$menudate = date("Y-m-d",strtotime("now + $w day"));
		if($updown == 2){
			$lm = 2;
			$sqlinsert = "INSERT INTO menudietexample (menudate,menumeal,foodid,foodcc,userid) VALUES ('$menudate','3','0','0','$userid')";
			mysql_query($sqlinsert);
		} else {
			$lm = 3;
		}
			for ($m=1;$m<=$lm;$m++) {
				$menu = array();
				$menuid = array();
				$totalcc = 0;
				$sql = "select foodid from food";
				$result = mysql_query($sql);
				$numfood = mysql_num_rows($result);
					for ($i=1;$i<=$numfood;$i++) {
						if ($totalcc <= $resultpermeal) {
							//echo $sql = "SELECT food.foodid, food.foodname, food.totalcallory FROM food WHERE food.foodid NOT IN (SELECT userdisease.diseaseid FROM userdisease WHERE userdisease.userid = '$userid' ) and food.totalcallory <= $resultpermeal AND food.foodid NOT IN ($strmenuid) order by rand()";
							$sql = "SELECT food.foodid, food.foodname, food.totalcallory FROM food WHERE food.status = '1' AND food.totalcallory <= $resultpermeal AND food.foodid NOT IN ($strmenuid) order by rand()";
							
							$result = mysql_query($sql);
							$row = mysql_fetch_array($result);
							$menu[] = $row;
							$totalcc = $totalcc+$row[2];
							$resultpermeal = $resultpermeal - $totalcc;
							$menuid[] = $row['0'];
							$strmenuid .= ",'$row[0]'";
							//print_r($row);
								if ($row[0]!=="") {
									$sqlinsert = "INSERT INTO menudietexample (menudate,menumeal,foodid,foodcc,userid) VALUES ('$menudate','$m','$row[0]','$row[2]','$userid')";
									mysql_query($sqlinsert);
							}
						} else {
						//echo $i;
							$strmenuid = $setstrmenuid;
							$totalcc = 0;
							$resultpermeal = $setpermeal;
							break;
						}
					}
			}
		}
		
		mysql_free_result($result);
		mysql_close($link);
		$menudate = date("d-m-Y");
		header("location: reportfood.php?reportday=$menudate");
	break;
	
	case "newtopic":
		$topictitle = $_POST["topictitle"];
		$topicdetail = $_POST["topicdetail"];
		$usid = $_SESSION["userid"];
		//$usid = "akejionioni";
		$ip = $_SERVER['REMOTE_ADDR'];
		$sql = "INSERT INTO webboardquestion (title, content, questiondate, ipaddress, userid) VALUES ('$topictitle', '$topicdetail', NOW(), '$ip', '$usid')";
		mysql_query($sql);
		$lastid = mysql_insert_id();
		mysql_close($link);
		header("Location: question.php?id=$lastid");		
	break;
	
	case "postcomment":
		$qid = $_POST["question"];
		$comment = $_POST["comment"];
		$ip = $_SERVER["REMOTE_ADDR"];
		$sql = "INSERT INTO webboardanswer (content, answerdate, ipaddress, questionid, userid) VALUES ( '$comment',now(),'$ip', '$qid', '$_SESSION[userid]');";
		mysql_query($sql);
		mysql_close($link);
		header("Location: question.php?id=$qid");
	break;
	
	case "reportweight":
		$weightreport = $_POST["weightreport"];
		$reportdescription = $_POST["reportdescription"];
		$sql = "INSERT INTO `reportweight` (`userid`, `reportdate`, `weight`, `description`) VALUES ('".$_SESSION["userid"]."', NOW(), '$weightreport', '$reportdescription')";
		mysql_query($sql);
		$sql = "UPDATE `userdata` SET `userweight`='$weightreport' WHERE `userid`='".$_SESSION["userid"]."'";
		mysql_query($sql);
		mysql_close($link);
		header("Location: reportweight.php");
	break;
	
	
}
?>